package com.kewu.system.service.impl;

import com.kewu.common.cons.file.FileMark;
import com.kewu.common.cons.file.FileType;
import com.kewu.common.enums.ErrorCodeEnum;
import com.kewu.common.global.CustomException;
import com.kewu.common.util.SnowflakeIdUtil;
import com.kewu.system.properties.FileProperties;
import com.kewu.system.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Slf4j
@Component("minioFileService")
@RequiredArgsConstructor
public class MinioFileService implements FileService {
    private final MinioClient minioClient;
    private final FileProperties fileProperties;

    @Override
    public String uploadFile(String filetype, MultipartFile file) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException {
        if (filetype.equals(getFileExtension(file.getOriginalFilename()))) {
            throw new CustomException(ErrorCodeEnum.FILE_EXTENSION_ERROR);
        }
        Long id = SnowflakeIdUtil.generateId();
        String filename = id + "-" + file.getOriginalFilename();
        log.info("filename:[{}]", filename);
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(fileProperties.getMinioBucket())
                .stream(file.getInputStream(), file.getSize(), -1)
                .build();
        minioClient.putObject(putObjectArgs);
        String minioURL = getMinioURL(filename);
        log.info("minio存储路径【{}】", minioURL);
        return minioURL;
    }

    @Override
    public InputStream downloadFile(FileType filetype, String localFile) {
        return null;
    }

    /**
     * 获取Minio的URL
     *
     * @param filename
     * @return
     */
    private String getMinioURL(String filename){
        return fileProperties.getMinioEndpoint() + FileMark.SIGNAL
                + fileProperties.getMinioBucket() + FileMark.SIGNAL + filename;
    }
}
